package com.liry.security.config;

import com.liry.security.domain.AuthConstant;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.stereotype.Component;

/**
 * 自定义的session存储器
 *
 * @author ALI
 * @since 2023/6/4
 */
@Component
public class CustomSecurityContextRepository implements SecurityContextRepository {


    @Override
    public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
        HttpServletRequest request = requestResponseHolder.getRequest();
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isBlank(token)) {
            return generateNewContext();
        }
        token = token.replace("Bearer ", "");
        SecurityContextImpl s = CacheManager.get(AuthConstant.buildLoginKey(token), SecurityContextImpl.class);
        if (s == null) {
            return generateNewContext();
        }
        return s;
    }

    @Override
    public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isBlank(token)) {
            token = response.getHeader(HttpHeaders.AUTHORIZATION);
        }
        if (StringUtils.isBlank(token)) {
            return;
        }
        token = token.replace("Bearer ", "");
        // 登录成功和失败的回调（LoginSuccessHandler，LoginFailureHandler）是在UsernamePasswordAuthenticationFilter过滤器里执行的
        // 而这里的认证信息缓存是在`SecurityContextPersistenceFilter`的doFilter后执行的
        // `SecurityContextPersistenceFilter`的顺序比`UsernamePasswordAuthenticationFilter`的顺序小，
        // 那么doFilter之后的方法就晚与LoginSuccessHandler，LoginFailureHandler
        CacheManager.set(AuthConstant.buildLoginKey(token), context);
    }

    @Override
    public boolean containsContext(HttpServletRequest request) {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isBlank(token)) {
            return false;
        }
        token = token.replace("Bearer ", "");
        return CacheManager.containsKey(AuthConstant.buildLoginKey(token));
    }

    protected SecurityContext generateNewContext() {
        return SecurityContextHolder.createEmptyContext();
    }

}
